<template>
  <div class="historical-records">
    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-item">
        <label>操作类型</label>
        <el-select 
          v-model="filterType" 
          placeholder="全部类型" 
          size="medium"
          @change="handleFilter"
          :loading="typeOptionsLoading"
          loading-text="加载中..."
        >
          <el-option 
            v-for="option in typeOptions" 
            :key="option.value"
            :label="option.label" 
            :value="option.value"
          ></el-option>
        </el-select>
      </div>

      <div class="filter-item">
        <label>日期范围</label>
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          size="medium"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="handleFilter"
        ></el-date-picker>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section">
      <div class="stat-card">
        <div class="stat-icon" style="background: #409EFF;">
          <i class="el-icon-document"></i>
        </div>
        <div class="stat-info">
          <div class="stat-value">{{ statistics.totalRecords }}</div>
          <div class="stat-label">总记录数</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon" style="background: #67C23A;">
          <i class="el-icon-time"></i>
        </div>
        <div class="stat-info">
          <div class="stat-value">{{ statistics.todayRecords }}</div>
          <div class="stat-label">今日操作</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon" style="background: #E6A23C;">
          <i class="el-icon-user"></i>
        </div>
        <div class="stat-info">
          <div class="stat-value">{{ statistics.lastLoginTime }}</div>
          <div class="stat-label">最后登录</div>
        </div>
      </div>
    </div>

    <!-- 操作记录列表 -->
    <div class="records-section">
      <div class="section-header">
        <div class="section-title">
          <i class="el-icon-files"></i>
          操作记录列表
        </div>
        <el-button 
          type="primary" 
          size="small"
          icon="el-icon-download"
          @click="handleExport"
          :loading="exportLoading"
        >
          导出记录
        </el-button>
      </div>

      <!-- 记录列表 -->
      <div v-if="filteredRecords.length > 0" class="records-list">
        <div 
          v-for="record in filteredRecords" 
          :key="record.id"
          class="record-item"
          @click="handleViewDetail(record)"
        >
          <div class="record-header">
            <div class="record-type">
              <span 
                class="type-tag" 
                :style="{ 
                  background: getTypeColor(record.operationType).bg,
                  color: getTypeColor(record.operationType).text 
                }"
              >
                {{ getTypeName(record.operationType) }}
              </span>
            </div>
            <div class="record-time">{{ record.operationTime }}</div>
          </div>
          <div class="record-content">
            <div class="record-title">{{ record.operationDesc }}</div>
            <div class="record-detail">{{ record.detail }}</div>
          </div>
          <div class="record-footer">
            <div class="record-meta">
              <span class="meta-item">
                <i class="el-icon-location"></i>
                {{ record.ipAddress }}
              </span>
              <span class="meta-item">
                <i class="el-icon-mobile-phone"></i>
                {{ record.device }}
              </span>
            </div>
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-state">
        <div class="empty-icon">
          <svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
            <!-- 文件夹图标 -->
            <rect x="60" y="80" width="80" height="60" rx="4" fill="#E8E8E8"/>
            <rect x="65" y="75" width="70" height="8" rx="2" fill="#D0D0D0"/>
            <!-- 文件图标 -->
            <rect x="75" y="95" width="50" height="4" rx="2" fill="#B0B0B0"/>
            <rect x="75" y="105" width="50" height="4" rx="2" fill="#B0B0B0"/>
            <rect x="75" y="115" width="35" height="4" rx="2" fill="#B0B0B0"/>
          </svg>
        </div>
        <p class="empty-text">暂无数据</p>
      </div>
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      title="操作详情"
      :visible.sync="detailDialogVisible"
      width="90%"
      :close-on-click-modal="false"
    >
      <div v-if="selectedRecord" class="detail-content">
        <div class="detail-row">
          <label>操作类型：</label>
          <span class="detail-value">{{ getTypeName(selectedRecord.operationType) }}</span>
        </div>
        <div class="detail-row">
          <label>操作描述：</label>
          <span class="detail-value">{{ selectedRecord.operationDesc }}</span>
        </div>
        <div class="detail-row">
          <label>详细信息：</label>
          <span class="detail-value">{{ selectedRecord.detail }}</span>
        </div>
        <div class="detail-row">
          <label>操作时间：</label>
          <span class="detail-value">{{ selectedRecord.operationTime }}</span>
        </div>
        <div class="detail-row">
          <label>IP地址：</label>
          <span class="detail-value">{{ selectedRecord.ipAddress }}</span>
        </div>
        <div class="detail-row">
          <label>设备信息：</label>
          <span class="detail-value">{{ selectedRecord.device }}</span>
        </div>
        <div class="detail-row">
          <label>操作模块：</label>
          <span class="detail-value">{{ selectedRecord.module }}</span>
        </div>
        <div class="detail-row">
          <label>操作结果：</label>
          <span 
            class="detail-value" 
            :style="{ color: selectedRecord.status === 'success' ? '#67C23A' : '#F56C6C' }"
          >
            {{ selectedRecord.status === 'success' ? '成功' : '失败' }}
          </span>
        </div>
      </div>
      <div slot="footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 导出确认对话框（移动端样式） -->
    <el-dialog
      title="导出确认"
      :visible.sync="showExportDialog"
      width="80%"
      center
      :close-on-click-modal="false"
    >
      <div class="export-confirm-content">
        <i class="el-icon-warning export-icon"></i>
        <p class="export-message">确定要导出当前筛选的历史记录吗？</p>
        <p class="export-count">共 {{ filteredRecords.length }} 条记录</p>
      </div>
      <div slot="footer" class="dialog-footer-mobile">
        <el-button @click="cancelExport" size="medium">取消</el-button>
        <el-button type="primary" @click="confirmExport" size="medium">确定导出</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getHistoricalRecords, exportRecords, getStatistics } from './service';

export default {
  name: 'HistoricalRecords',

  data() {
    return {
      filterType: '',
      dateRange: [],
      records: [],
      filteredRecords: [],
      statistics: {
        totalRecords: 0,
        todayRecords: 0,
        lastLoginTime: '--'
      },
      exportLoading: false,
      detailDialogVisible: false,
      selectedRecord: null,
      showExportDialog: false,
      typeOptionsLoading: true,
      typeOptions: []
    };
  },

  methods: {
    // 移动端Toast提示
    showToast(message, type = 'success') {
      this.$notify({
        title: '',
        message: message,
        type: type,
        duration: 2000,
        position: 'top-right',
        offset: 60,
        customClass: 'mobile-toast'
      });
    },

    // 加载操作类型选项（延迟1秒）
    loadTypeOptions() {
      this.typeOptionsLoading = true;
      setTimeout(() => {
        this.typeOptions = [
          { label: '全部类型', value: '' },
          { label: '登录', value: 'login' },
          { label: '查看', value: 'view' },
          { label: '编辑', value: 'edit' },
          { label: '导出', value: 'export' },
          { label: '删除', value: 'delete' },
          { label: '创建', value: 'create' }
        ];
        this.typeOptionsLoading = false;
      }, 1000);
    },

    // 加载历史记录
    loadRecords() {
      const loading = this.$loading({
        lock: true,
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      Promise.all([
        getHistoricalRecords(),
        getStatistics()
      ]).then(([records, stats]) => {
        this.records = records;
        this.filteredRecords = records;
        this.statistics = stats;
        loading.close();
      }).catch(error => {
        loading.close();
        this.showToast(error.message || '加载失败', 'error');
      });
    },

    // 筛选处理
    handleFilter() {
      let filtered = [...this.records];

      // 按类型筛选
      if (this.filterType) {
        filtered = filtered.filter(record => record.operationType === this.filterType);
      }

      // 按日期范围筛选
      if (this.dateRange && this.dateRange.length === 2) {
        const [startDate, endDate] = this.dateRange;
        filtered = filtered.filter(record => {
          const recordDate = record.operationTime.split(' ')[0];
          return recordDate >= startDate && recordDate <= endDate;
        });
      }

      this.filteredRecords = filtered;
    },

    // 导出记录
    handleExport() {
      if (this.filteredRecords.length === 0) {
        this.showToast('暂无数据可导出', 'warning');
        return;
      }

      this.showExportDialog = true;
    },

    // 确认导出
    confirmExport() {
      this.showExportDialog = false;
      this.exportLoading = true;

      exportRecords(this.filteredRecords).then(result => {
        this.exportLoading = false;
        
        // 创建下载链接
        const blob = new Blob([result.data], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        const url = URL.createObjectURL(blob);
        
        link.setAttribute('href', url);
        link.setAttribute('download', result.filename);
        link.style.visibility = 'hidden';
        
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        this.$notify({
          title: '✅ 导出成功',
          message: '历史记录已导出',
          type: 'success',
          duration: 2500,
          position: 'top-right',
          offset: 60,
          customClass: 'mobile-toast-large'
        });
      }).catch(error => {
        this.exportLoading = false;
        this.showToast(error.message || '导出失败', 'error');
      });
    },

    // 取消导出
    cancelExport() {
      this.showExportDialog = false;
    },

    // 查看详情
    handleViewDetail(record) {
      this.selectedRecord = record;
      this.detailDialogVisible = true;
    },

    // 获取类型名称
    getTypeName(type) {
      const typeMap = {
        'login': '登录',
        'view': '查看',
        'edit': '编辑',
        'export': '导出',
        'delete': '删除',
        'create': '创建'
      };
      return typeMap[type] || type;
    },

    // 获取类型颜色
    getTypeColor(type) {
      const colorMap = {
        'login': { bg: '#E1F3FF', text: '#409EFF' },
        'view': { bg: '#F0F9FF', text: '#909399' },
        'edit': { bg: '#FDF6EC', text: '#E6A23C' },
        'export': { bg: '#F0F9FF', text: '#67C23A' },
        'delete': { bg: '#FEF0F0', text: '#F56C6C' },
        'create': { bg: '#F0F9FF', text: '#67C23A' }
      };
      return colorMap[type] || { bg: '#F5F7FA', text: '#909399' };
    }
  },

  mounted() {
    this.loadTypeOptions();
    this.loadRecords();
  }
};
</script>

<style scoped>
.historical-records {
  background: #f5f5f5;
  min-height: 100%;
  padding: 15px;
  padding-bottom: 20px;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

/* 筛选区域 */
.filter-section {
  background: white;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.filter-item {
  margin-bottom: 15px;
}

.filter-item:last-child {
  margin-bottom: 0;
}

.filter-item label {
  display: block;
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  font-weight: 500;
}

.filter-item >>> .el-select,
.filter-item >>> .el-date-editor {
  width: 100%;
}

/* 统计信息 */
.stats-section {
  display: flex;
  gap: 8px;
  margin-bottom: 15px;
  flex-wrap: nowrap;
}

.stat-card {
  flex: 1;
  min-width: 0;
  background: white;
  border-radius: 8px;
  padding: 12px 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.stat-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
  flex-shrink: 0;
}

.stat-icon i {
  font-size: 20px;
  color: white;
}

.stat-info {
  text-align: center;
  width: 100%;
}

.stat-value {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.stat-label {
  font-size: 11px;
  color: #999;
  white-space: nowrap;
}

/* 操作记录区域 */
.records-section {
  background: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  display: flex;
  align-items: center;
}

.section-title i {
  margin-right: 6px;
  color: #409EFF;
  font-size: 18px;
}

/* 记录列表 */
.records-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.record-item {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  padding: 12px;
  cursor: pointer;
  transition: all 0.3s;
  background: #fafafa;
}

.record-item:active {
  background: #f5f5f5;
  transform: scale(0.98);
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.type-tag {
  display: inline-block;
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.record-time {
  font-size: 12px;
  color: #999;
}

.record-content {
  margin-bottom: 10px;
}

.record-title {
  font-size: 15px;
  font-weight: 500;
  color: #333;
  margin-bottom: 5px;
}

.record-detail {
  font-size: 13px;
  color: #666;
  line-height: 1.5;
}

.record-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.record-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.meta-item {
  font-size: 12px;
  color: #999;
  display: flex;
  align-items: center;
}

.meta-item i {
  margin-right: 4px;
  font-size: 14px;
}

.record-footer > i {
  color: #ccc;
  font-size: 16px;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 80px 20px;
  background: white;
  border-radius: 8px;
}

.empty-icon {
  width: 120px;
  height: 120px;
  margin: 0 auto 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-icon svg {
  width: 100%;
  height: 100%;
  opacity: 0.6;
}

.empty-text {
  font-size: 14px;
  color: #999;
  margin: 0;
  line-height: 1.5;
}

/* 详情对话框 */
.detail-content {
  padding: 10px 0;
}

.detail-row {
  display: flex;
  margin-bottom: 15px;
  font-size: 14px;
}

.detail-row:last-child {
  margin-bottom: 0;
}

.detail-row label {
  width: 90px;
  color: #666;
  font-weight: 500;
  flex-shrink: 0;
}

.detail-value {
  flex: 1;
  color: #333;
  word-break: break-all;
}

/* 导出确认对话框样式 */
.export-confirm-content {
  text-align: center;
  padding: 20px 0;
}

.export-icon {
  font-size: 50px;
  color: #E6A23C;
  margin-bottom: 15px;
}

.export-message {
  font-size: 16px;
  color: #333;
  margin: 0 0 10px 0;
  line-height: 1.6;
}

.export-count {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.dialog-footer-mobile {
  display: flex;
  gap: 10px;
  padding: 0;
}

.dialog-footer-mobile .el-button {
  flex: 1;
  margin: 0;
  border-radius: 4px;
}

/* 对话框移动端优化 */
.historical-records >>> .el-dialog {
  border-radius: 12px;
}

.historical-records >>> .el-dialog__header {
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.historical-records >>> .el-dialog__title {
  font-size: 16px;
  font-weight: 600;
}

.historical-records >>> .el-dialog__body {
  padding: 20px;
}

.historical-records >>> .el-dialog__footer {
  padding: 15px 20px;
  border-top: 1px solid #f0f0f0;
}

/* 响应式调整 */
@media (max-width: 400px) {
  .stats-section {
    gap: 6px;
  }
  
  .stat-card {
    padding: 10px 6px;
  }
  
  .stat-icon {
    width: 35px;
    height: 35px;
    margin-bottom: 6px;
  }
  
  .stat-icon i {
    font-size: 18px;
  }
  
  .stat-value {
    font-size: 14px;
  }
  
  .stat-label {
    font-size: 10px;
  }
}
</style>

